<template>
  <div class="p-3">
    <a-card style="height: 820px" :bordered="false">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="操作时间" name="time">
          <a-range-picker
            style="width: 250px"
            v-model:value="searchForm.time"
          ></a-range-picker>
        </a-form-item>
        <a-form-item label="归属机构" name="comId">
          <a-tree-select
            v-model:value="searchForm.comId"
            tree-node-filter-prop="label"
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择归属机构"
          />
        </a-form-item>
        <a-form-item label="操作人" name="operator">
          <a-select
            style="width: 150px"
            placeholder="请选择操作人"
            v-model:value="searchForm.operator"
          ></a-select>
        </a-form-item>
        <a-form-item label="合同名称" name="contractName">
          <a-input
            style="width: 150px"
            placeholder="请输入合同名称"
            v-model:value="searchForm.contractName"
          ></a-input>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onSearch"
            ><SearchOutlined />查询</a-button
          >
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="showAddModal"
            ><PlusOutlined />新增</a-button
          >
        </a-form-item>
      </a-form>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        class="mt-3"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == 'contractApp'">
            <a-button type="link" :href="record.contractApp">点击下载附件</a-button>
          </template>
          <template v-if="column.dataIndex == 'photo'">
            <a-image :width="100" :src="record.photo" />
          </template>
          <template v-if="column.dataIndex == 'action'">
            <a-span>
              <a-button type="link" @click="showEditModal(record)"
                >编辑</a-button
              >
              <a-popconfirm
                title="确定删除该合同吗？"
                placement="bottom"
                ok-text="是"
                cancel-text="否"
                @confirm="confirmDelete(record.id)"
              >
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>
              <a-button type="link">附件下载</a-button>
            </a-span>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增合同弹窗 -->
    <a-modal
      v-model:visible="addModalVisible"
      title="新增合同"
      width="800px"
      :footer="null"
    >
      <a-form
        :model="formData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="合同名称" name="contractName">
          <a-input
            v-model:value="formData.contractName"
            placeholder="请输入合同名称"
          />
        </a-form-item>
        <a-form-item label="合同标题" name="contractTitle">
          <a-input
            v-model:value="formData.contractTitle"
            @input="formData.contractTitle = $event.target.value"
            placeholder="请输入合同标题"
          />
        </a-form-item>
        <a-form-item label="归属机构" name="comId">
          <a-tree-select
            v-model:value="formData.comId"
            tree-node-filter-prop="label"
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择归属机构"
          />
        </a-form-item>
        <a-form-item label="合同内容" name="contractContent">
          <!-- <TinyMce v-model:value="formData.contractContent" /> -->
          <a-input
            v-model:value="formData.contractContent"
            placeholder="请输入合同内容"
          />
        </a-form-item>

        <a-form-item label="附件" name="contractApp">
          <a-upload
            v-model:file-list="fileLists"
            :before-upload="beforeUploads"
            @remove="handleRemove"
            :headers="header"
            @change="handleChanges"
            accept=".pdf"
            action="/api/ChargeSystem/contract/uploadContract"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              选择文件
            </a-button>
          </a-upload>
        </a-form-item>
        <a-form-item label="电子章" name="photo">
          <a-upload
            v-model:file-list="fileList"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            accept=".png,.jpg,.jpeg,.gif,.bmp"
            action="/api/ChargeSystem/contract/uploadContract"
            :before-upload="beforeUpload"
            @change="handleChange"
            :headers="header"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
            <div v-else>
              <loading-outlined v-if="loading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="手写签名">
          <a-switch :checked="checked" @change="checked = $event" />
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 6, span: 18 }">
          <a-space>
            <a-button type="primary" @click="handleSubmit">保存</a-button>
            <a-button @click="handleCancel">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import {
  SearchOutlined,
  PlusOutlined,
  UploadOutlined,
  LoadingOutlined,
} from '@ant-design/icons-vue';
import * as netData from '#/api/core/setting';
import { getCompanyTree } from '#/api/core/develop';
import { message } from 'ant-design-vue';
import { useAccessStore } from '@vben/stores';

import dayjs from 'dayjs';

// import TinyMce from '#/components/Editor/TinyMce.vue';

const accessStore = useAccessStore();
const searchForm = reactive({
  comId: '',
  operator: '',
  contractName: '',
  time: '',
});
const columns = [
  {
    title: '归属机构',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '合同编号',
    dataIndex: 'contractNumber',
    key: 'contractNumber',
    align: 'center',
  },
  {
    title: '合同名称',
    dataIndex: 'contractName',
    key: 'contractName',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
    align: 'center',
  },
  {
    title: '附件',
    dataIndex: 'contractApp',
    key: 'contractApp',
    align: 'center',
  },
  {
    title: '图片',
    dataIndex: 'photo',
    key: 'photo',
    align: 'center',
  },
  {
    title: '操作时间',
    dataIndex: 'operatorTime',
    key: 'operatorTime',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
  },
];
const header = {
  Authorization: accessStore.accessToken || localStorage.getItem('token'),
};
const dataSource = ref([]);
const loading = ref<boolean>(false);
const imageUrl = ref<string>('');
const checked = ref<boolean>(false);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const onSearch = () => {
  const query = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    comId: searchForm.comId,
    operator: searchForm.operator,
    contractName: searchForm.contractName,
    time: searchForm.time
      ? `${dayjs(searchForm.time[0]).format('YYYY-MM-DD')},${dayjs(
          searchForm.time[1],
        ).format('YYYY-MM-DD')}`
      : '',
  };
  netData.getContractInfo(query).then((res: any) => {
    console.log(res);
    dataSource.value = res.data;
    pagination.total = res.total;
  });
};

onMounted(() => {
  getTableData();
});
type TreeNode = {
  key: string | number;
  label: string;
  value: string | number;
  isLeaf: boolean;
  children: TreeNode[];
};

const comanyList = ref<TreeNode[]>([]);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): TreeNode[] => {
      console.log(tree);
      return tree.map((item: any): TreeNode => {
        const processedItem: TreeNode = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
    console.log(comanyList.value);
  });
};
// 新增/编辑弹窗相关
const addModalVisible = ref(false);
const isEdit = ref(false);
const editId = ref<number | null>(null);
const formData = reactive({
  comId: '',
  contractName: '',
  contractTitle: '',
  organization: '',
  contractContent: '',
  contractApp: [],
  photo: [],
});
const fileList = ref<any[]>([]);
const fileLists = ref<any[]>([]);

// 显示新增弹窗
const showAddModal = () => {
  isEdit.value = false;
  editId.value = null;
  resetForm();
  addModalVisible.value = true;
};

// 显示编辑弹窗
const showEditModal = (record: any) => {
  isEdit.value = true;
  editId.value = record.id;
  // 将记录数据赋值到表单
  formData.comId = record.comId || '';
  formData.contractName = record.contractName || '';
  formData.contractTitle = record.contractTitle || '';
  formData.organization = record.organization || '';
  formData.contractContent = record.contractContent || '';
  formData.contractApp = record.contractApp || '';
  formData.photo = record.photo || '';
  addModalVisible.value = true;
};

// 重置表单
const resetForm = () => {
  formData.comId = '';
  formData.contractName = '';
  formData.contractTitle = '';
  formData.organization = '';
  formData.contractContent = '';
  formData.contractApp = '';
  formData.photo = '';
  fileList.value = [];
  imageUrl.value = '';
  checked.value = false;
};

// 取消
const handleCancel = () => {
  addModalVisible.value = false;
  resetForm();
  isEdit.value = false;
  editId.value = null;
};

// 提交
const handleSubmit = () => {
  console.log(fileLists.value, fileLists.value);
  if (!formData.contractName) {
    message.error('请输入合同名称');
    return;
  }
  if (!formData.contractContent) {
    message.error('请输入合同内容');
    return;
  }

  const query = {
    comId: formData.comId ?? '',
    contractName: formData.contractName ?? '',
    contractTitle: formData.contractTitle ?? '',
    organization: formData.organization ?? '',
    contractContent: formData.contractContent ?? '',
    contractApp: contractApp.value ?? '',
    photo: photo.value ?? '',
  };

  if (isEdit.value && editId.value) {
    // 编辑模式
    const editQuery = { ...query, id: editId.value };
    netData.editContractInfo(editQuery).then((res: any) => {
      console.log(res);
      if (res === 1) {
        message.success('编辑成功');
        handleCancel();
        onSearch(); // 刷新列表
      } else {
        message.error('编辑失败');
      }
    });
  } else {
    // 新增模式
    netData.addContractInfo(query).then((res: any) => {
      console.log(res);
      if (res === 1) {
        message.success('添加成功');
        handleCancel();
        onSearch(); // 刷新列表
      } else {
        message.error('添加失败');
      }
    });
  }
};

// 文件上传前处理
const beforeUploads = (file: any) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('文件大小不能超过10MB!');
    return false;
  } else {
    fileLists.value = [...fileLists.value, file];
    return true;
  }
};
// 文件上传前处理
const beforeUpload = (file: any) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('文件大小不能超过10MB!');
    return false;
  } else {
    fileList.value = [...fileList.value, file];
    return true;
  }
};
// 移除文件
const handleRemove = (file: any) => {
  const index = fileLists.value.indexOf(file);
  const newFileList = fileLists.value.slice();
  newFileList.splice(index, 1);
  fileLists.value = newFileList;
};
const contractApp = ref('')
// 图片上传状态变化
const handleChanges = (info: any) => {
  console.log(info);
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    if (info.file.response.code === 500) {
      message.error(info.file.response.data);
      loading.value = false;
      //清除文件列表
      fileLists.value = [];
      return;
    } else if (info.file.response.code === 200) {
      loading.value = false;
      message.success('上传成功');
      contractApp.value = info.file.response.data
      imageUrl.value = info.file.response.url || info.file.thumbUrl;
    } else {
      loading.value = false;
      message.error('上传失败');
    }
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('上传失败');
  }
};
const photo = ref('')
const handleChange = (info: any) => {
  console.log(info);
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    if (info.file.response.code === 500) {
      message.error(info.file.response.data);
      loading.value = false;
      //清除文件列表
      fileList.value = [];
      return;
    } else if (info.file.response.code === 200) {
      loading.value = false;
      message.success('上传成功');
      photo.value = info.file.response.data
      imageUrl.value = info.file.response.msg || info.file.thumbUrl;
    } else {
      loading.value = false;
      message.error('上传失败');
    }
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('上传失败');
  }
};
const confirmDelete = (id: number) => {
  netData.delContractInfo(id).then((res: any) => {
    console.log(res);
    if (res === 1) {
      message.success('删除成功');
      onSearch();
    } else {
      message.error('删除失败');
    }
  });
};
</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
:deep(.ant-modal) {
  z-index: 999 !important;
}

/* TinyMCE 编辑器 z-index 设置 */
:deep(.tox) {
  z-index: 9999 !important;
}

:deep(.tox-tinymce) {
  z-index: 9999 !important;
}

:deep(.tox-editor-container) {
  z-index: 9999 !important;
}

:deep(.tox-menubar) {
  z-index: 9999 !important;
}

:deep(.tox-toolbar-overlord) {
  z-index: 9999 !important;
}

:deep(.tox-toolbar) {
  z-index: 9999 !important;
}

:deep(.tox-edit-area) {
  z-index: 9999 !important;
}

:deep(.tox-statusbar) {
  z-index: 9999 !important;
}

/* 弹出层和下拉菜单 */
:deep(.tox-menu) {
  z-index: 10000 !important;
}

:deep(.tox-collection) {
  z-index: 10000 !important;
}

:deep(.tox-pop) {
  z-index: 10000 !important;
}

:deep(.tox-dialog-wrap) {
  z-index: 10001 !important;
}

:deep(.tox-dialog) {
  z-index: 10001 !important;
}

:deep(.tox-dialog__backdrop) {
  z-index: 10000 !important;
}

/* 工具提示 */
:deep(.tox-tooltip) {
  z-index: 10002 !important;
}

/* 全屏模式 */
:deep(.tox-fullscreen) {
  z-index: 10003 !important;
}
:deep(.tox .tox-dialog-wrap) {
  z-index: 9999 !important;
}
</style>
